﻿using ERPSystem.Common.Domains.Delivergoods;
using ERPSystem.Common.Domains.SalesOrderCommom;
using ERPSystem.Common.DTO;
using ERPSystem.Common.Infrastructure.IRepository;
using MediatR;
using Microsoft.AspNetCore.StaticFiles;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using SalesManagementCommon.API.SalesManagementCommons.Shippingnotess;

namespace SalesManagementCommon.API.SalesManagementCommons.OutOfStock
{
    public class OutOfStockExcelHander : IRequestHandler<OutOfStockExcelCommand, FileExportResult>
    {
        private readonly IBaseRepository<SaleOutOfWarehouse> saleOutOfWarehouseRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="saleOutOfWarehouseRepository"></param>
        public OutOfStockExcelHander(IBaseRepository<SaleOutOfWarehouse> saleOutOfWarehouseRepository)
        {
            this.saleOutOfWarehouseRepository = saleOutOfWarehouseRepository;
        }

        public async Task<FileExportResult> Handle(OutOfStockExcelCommand request, CancellationToken cancellationToken)
        {
            var result = new FileExportResult();

            var list = await(await saleOutOfWarehouseRepository.GetAll()).ToListAsync();
            Console.WriteLine(list.Count);
            IWorkbook book = new XSSFWorkbook();
            ISheet sheet = book.CreateSheet();
            IRow row1 = sheet.CreateRow(0);

            row1.CreateCell(0).SetCellValue("序号");
            row1.CreateCell(1).SetCellValue("单据编码");
            row1.CreateCell(2).SetCellValue("单据状态");
            row1.CreateCell(3).SetCellValue("物料编码");
            row1.CreateCell(4).SetCellValue("单据日期");
            int rowIndex = 0;
            foreach (var item in list)
            {
                row1 = sheet.CreateRow(rowIndex);
                row1.CreateCell(0).SetCellValue(item.SaleOutOfWarehouseId);
                row1.CreateCell(1).SetCellValue(item.DocumentNumber);
                row1.CreateCell(2).SetCellValue(item.DocumentStatus);
                row1.CreateCell(3).SetCellValue(item.ItemBianma);
                row1.CreateCell(4).SetCellValue(item.DocumentDate);
                rowIndex++;
            }
            byte[] data = null;
            using (MemoryStream ms = new MemoryStream())
            {
                book.Write(ms);
                data = ms.ToArray();
            }
            string contextType = new FileExtensionContentTypeProvider().Mappings[".xlsx"];
            string fileName = "出库单.xlsx";

            result.FileBytes = data;
            result.MimeType = contextType;
            result.FileName = fileName;
            return result;
        }
    }
}
